package com.wlb365.admin.common.aspect;

import cn.hutool.core.util.ObjectUtil;
import com.wlb365.admin.common.annotation.DataScope;
import com.wlb365.admin.common.constants.SysConstant;
import com.wlb365.admin.common.support.entity.BaseEntity;
import com.wlb365.admin.common.utils.ShiroUtil;
import com.wlb365.admin.common.utils.StringUtils;
import com.wlb365.admin.modules.sys.entity.Role;
import com.wlb365.admin.modules.sys.entity.User;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 数据权限拦截器.
 *
 * @author zwh
 * @version 1.0
 */
@Aspect
@Component
public class DataScopeAspect {
    /**
     * 全部数据权限.
     */
    public static final String DATA_SCOPE_ALL = "1";

    /**
     * 自定数据权限.
     */
    public static final String DATA_SCOPE_CUSTOM = "2";

    /**
     * 部门数据权限.
     */
    public static final String DATA_SCOPE_DEPT = "3";

    /**
     * 部门及以下数据权限.
     */
    public static final String DATA_SCOPE_DEPT_AND_CHILD = "4";

    /**
     * 仅本人数据权限.
     */
    public static final String DATA_SCOPE_SELF = "5";

    /**
     * 数据权限过滤关键字.
     */
    public static final String DATA_SCOPE = "dataScope";

    /**
     * 切面：织入点
     */
    @Pointcut("@annotation(com.wlb365.admin.common.annotation.DataScope)")
    public void dataScopePointCut () {
    }

    /**
     * 切面处理.
     * @param point point.
     * @throws Throwable 异常
     */
    @Before("dataScopePointCut()")
    public void doBefore (JoinPoint point) throws Throwable {
        handleDataScope(point);
    }

    /**
     * 数据权限处理.
     * @param joinPoint point.
     */
    protected void handleDataScope (final JoinPoint joinPoint) {
        // 获得注解
        DataScope controllerDataScope = getAnnotationLog(joinPoint);
        if (controllerDataScope == null) {
            return;
        }
        // 获取当前的用户
        User currentUser = ShiroUtil.getUser();
        if (currentUser != null) {
            // 如果是超级管理员，则不过滤数据
            if (!SysConstant.ADMIN.equals(currentUser.getUsername())) {
                dataScopeFilter(joinPoint, currentUser, controllerDataScope.deptAlias(),
                        controllerDataScope.userAlias());
            }
        }

    }

    public static void dataScopeFilter(JoinPoint joinPoint, User user, String deptAlias, String userAlias) {
        StringBuilder sqlString = new StringBuilder();
        for (Role role : user.getRoles()) {
            String dataScope = role.getDataScope();
            if (DATA_SCOPE_ALL.equals(dataScope))
            {
                sqlString = new StringBuilder();
                break;
            }
            else if (DATA_SCOPE_CUSTOM.equals(dataScope))
            {
                sqlString.append(StringUtils.format(
                        " OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias,
                        role.getId()));
            } else if (DATA_SCOPE_DEPT.equals(dataScope)) {
                if (StringUtils.isEmpty(deptAlias)) {
                    //未定义别名
                    sqlString.append(StringUtils.format(" OR dept_id = {} ", user.getDeptId()));
                } else {
                    sqlString.append(StringUtils.format(" OR {}.dept_id = {} ", deptAlias, user.getDeptId()));
                }

            }
        }

        if (StringUtils.isNotEmpty(sqlString.toString()))
        {
            Object params = joinPoint.getArgs()[0];
            if (ObjectUtil.isNotEmpty(params) && params instanceof BaseEntity)
            {
                BaseEntity baseEntity = (BaseEntity) params;
                baseEntity.getCondition().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")");
            }
        }
    }

    /**
     * 是否存在注解，如果存在就获取.
     * @param joinPoint point.
     * @return 注解.
     */
    private DataScope getAnnotationLog(JoinPoint joinPoint)
    {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null)
        {
            return method.getAnnotation(DataScope.class);
        }
        return null;
    }

}
